<?php

namespace common\service;

use common\model\SupplierModel;
use common\model\TenantGroupMemberModel;
use common\model\TenantUserModel;
use common\model\TenantAuthenticationModel;
use common\model\TenantStepCategoryLevelModel;
use common\model\UserModel;
use support\ErrorCode;

class CustomerService
{

    /**
     * 获取客户列表
     * @param $param
     * @param $filter
     * @param $currentTenantId
     * @return array
     */
    protected function select($param, $filter, $currentTenantId)
    {

        if (array_key_exists('page', $param)) {
            $page = join(',', $param['page']);
        } else {
            $maxPageSize = C("database.database_max_select_rows");
            $page = "1, {$maxPageSize}";
        }


        $supplierModel = model(SupplierModel::class);

        // 获取总行数
        $total = $supplierModel
            ->join("LEFT JOIN tenant ON tenant.id=supplier.from_tenant_id")
            ->join("LEFT JOIN tenant_authentication ON tenant_authentication.tenant_id = supplier.tenant_id")
            ->where($filter)->field('count(distinct supplier.id ) as total')->find();

        $total = $total['total'] ?? 0;
        // 查询数据
        $data = [];
        if ($total > 0) {
            $queryFields = [
                'supplier.id',
                'supplier.user_id',
                'supplier.type',
                'supplier.tenant_id',
                'supplier.from_tenant_id',
                'supplier.step_category_ids',
                'supplier.created',
                'supplier.updated',
                'supplier.created_by',
                'supplier.framework_agreement_contract_id',
                'supplier.framework_agreement_status',
                'supplier.confirm_status',
                'supplier.create_tenant_id',
            ];
            $data = $supplierModel
                ->join("LEFT JOIN tenant ON tenant.id=supplier.from_tenant_id")
                ->join("LEFT JOIN tenant_authentication ON tenant_authentication.tenant_id = supplier.tenant_id")
                ->field(implode(',', $queryFields))
                ->where($filter)
                ->page($page)
                ->order('created desc')
                ->select();
            $tenantAuthenticationModel = model(TenantAuthenticationModel::class);
            $tenantIds = array_column($data, 'tenant_id', 'tenant_id');

            $userIds = array_column($data, 'user_id', 'user_id');
            $createdByIds = array_column($data, 'created_by', 'created_by');
            $userIds = array_merge($userIds, $createdByIds);
            $users = [];
            if (!empty($userIds)) {
                $users = model(UserModel::class)->where(['id' => ['IN', implode(',', $userIds)]])->select();
                $users = array_column($users, null, 'id');
            }

            // 查询当前租户下所有的集团
            $nowTenantGroupIds = model(TenantGroupMemberModel::class)->where(['tenant_id' => $currentTenantId])->column('tenant_group_id');

            // 查询客户所在的集团
            $customerTenantIds = array_column($data, 'tenant_id');
            $customerGroupData = model(TenantGroupMemberModel::class)->where(['tenant_id' => ['IN', $customerTenantIds]])->field('tenant_id,tenant_group_id')->select();
            $customerGroupMap = array_group_by($customerGroupData, 'tenant_id');

            if (!empty($tenantIds)) {
                $tenantAuthenticationData = $tenantAuthenticationModel->where(['tenant_id' => ['IN', implode(',', $tenantIds)]])
                    ->field("fdd_auth_status_desc,reasons_for_failure,secrecy_level,company_customer_service,service_category,json,company_business_scope,unified_social_credit_code,company_registered_address,legal_id_period_end,legal_phone,legal_id_number,fdd_auth_url,fdd_transaction_no", true)
                    ->select();
                if (!empty($tenantAuthenticationData)) {
                    //每个供应商 对应不同分类的等级数据
                    $tenantAuthenticationDataAssoc = array_column($tenantAuthenticationData, null, 'tenant_id');
                    $tenantStepCategoryLevelModel = model(TenantStepCategoryLevelModel::class);
                    $tenantStepCategoryLevelData = $tenantStepCategoryLevelModel
                        ->where([
                            'tenant_id' => ['IN', implode(',', $tenantIds)]
                        ])
                        ->field("uuid,created,updated,created_by", true)
                        ->select();
                    $tenantStepCategoryLevelData = array_group_by($tenantStepCategoryLevelData, 'tenant_id');
                    $data = array_map(function ($item) use ($tenantAuthenticationDataAssoc, $tenantStepCategoryLevelData, $users, $customerGroupMap, $nowTenantGroupIds) {
                        $item['authentication'] = $tenantAuthenticationDataAssoc[$item['tenant_id']] ?? null;
                        $item['level_data'] = $tenantStepCategoryLevelData[$item['tenant_id']] ?? null;
                        $item['creator'] = $users[$item['created_by']] ?? null;
                        $item['user'] = $users[$item['user_id']] ?? null;
                        $customerGroupTenantList = $customerGroupMap[$item['tenant_id']] ?? [];
                        $customerGroupTenantIds = array_column($customerGroupTenantList, 'tenant_group_id');
                        $item['tenant_group_in'] = boolval(array_intersect($nowTenantGroupIds, $customerGroupTenantIds)); // 是否集团内
                        $item['customer_group_tenant_list'] = $customerGroupTenantIds;
                        $item['now_tenant_group_ids'] = $nowTenantGroupIds;
                        return $item;
                    }, $data);
                }

            }
        }

        return [
            "total" => $total,
            "rows" => $data
        ];
    }


    /**
     * 获取供应商列表 tenant_id 为当前租户
     * @param $currentUserId
     * @param $param
     * @param $currentTenantId
     * @return array
     * @throws \Exception
     */
    public function getCustomerList($currentUserId, $param, $currentTenantId)
    {
        $tenantUserModel = model(TenantUserModel::class);
        $tenantUser = $tenantUserModel
            ->where([
                'user_id' => $currentUserId,
                'status' => 'active',
            ])
            ->find();

        if (empty($tenantUser)) {
            throw_strack_exception('Illegal operation', ErrorCode::ILLEGAL_OPERATION);
        }

        $filter = [
            'supplier.from_tenant_id' => $tenantUser['tenant_id'],
//            'tenant_authentication.status' => "active",
//            'tenant_authentication.fdd_auth_status' => 4,
//            'tenant_authentication.fdd_cert_status' => 1,
            'supplier.type' => "outside",
        ];
        if (isset($param['filter'])) {
            $stepCategoryIdFilter = $param['filter']['supplier.step_category_ids'] ?? null;
            $groupTenantType = $param['filter']['group_tenant_type'] ?? null;

            // 支持框架合同状态筛选
            if (!empty($param['filter']['framework_agreement_status'])) {
                $businessMode = OptionsService::getInstance()->getBusinessMode();
                if ($businessMode === OptionsService::BUSINESS_MODE_BOTH_SIDES) {
                    $filter[] = [
                        [
                            'supplier.framework_agreement_status' => $param['filter']['framework_agreement_status'],
                            'supplier.type' => 'outside',
                        ],
                        'supplier.type' => 'inside',
                        '_logic' => 'or'
                    ];
                    $filter['supplier.framework_agreement_status'] = $param['filter']['framework_agreement_status'];
                } else if ($businessMode === OptionsService::BUSINESS_MODE_TRIPARTITE) {
                    $filter[] = [
                        [
                            'tenant.framework_agreement_status' => $param['filter']['framework_agreement_status'],
                            'supplier.type' => 'outside',
                        ],
                        'supplier.type' => 'inside',
                        '_logic' => 'or'
                    ];
                }
            }

            // 认证状态
            if (!empty($param['filter']['tenant_authentication_status'])) {
                $filter['tenant_authentication.status'] = [
                    'IN',
                    (array)$param['filter']['tenant_authentication_status']
                ];
            }
            unset($param['filter']['supplier.step_category_ids'], $param['filter']['group_tenant_type'], $param['filter']['framework_agreement_status'], $param['filter']['tenant_authentication_status']);

            if (isset($groupTenantType)) {
                // 集团 内部还是外部
                if ($groupTenantType == 'inside') { // 内部
                    $tenantGroupData = model(TenantGroupMemberModel::class)->where(['tenant_id' => $currentTenantId])->column('tenant_group_id');
                    $tenantGroupInsideIds = model(TenantGroupMemberModel::class)->where(['tenant_group_id' => ['IN', $tenantGroupData]])->column('tenant_id');
                    $filter[] = [
                        'supplier.tenant_id' => [
                            'IN', $tenantGroupInsideIds
                        ]
                    ];
                } elseif ($groupTenantType == 'outside') { // 外部
                    $tenantGroupData = model(TenantGroupMemberModel::class)->where(['tenant_id' => $currentTenantId])->column('tenant_group_id');
                    $tenantGroupInsideIds = model(TenantGroupMemberModel::class)->where(['tenant_group_id' => ['IN', $tenantGroupData]])->column('tenant_id');
                    $filter[] = [
                        'supplier.tenant_id' => [
                            'NOT IN', $tenantGroupInsideIds
                        ]
                    ];
                }
            }

            $filter = array_merge($filter, $param['filter']);
        }


        if (!empty($stepCategoryIdFilter)) {
            $stepCategoryIdFilterValues = '';
            foreach ($stepCategoryIdFilter as $stepCategoryIdFilterValue) {
                $stepCategoryIdFilterValues .= "FIND_IN_SET('{$stepCategoryIdFilterValue}' , supplier.step_category_ids) OR ";
            }
            $stepCategoryIdFilterValues = trim($stepCategoryIdFilterValues, ' OR');
            $filter[] = [
                '_string' => $stepCategoryIdFilterValues
            ];
        }

        return $this->select($param, $filter, $currentTenantId);
    }

    /**
     * 查询客户
     * @param int $tenantId 当前租户id
     * @param array $param
     * @return mixed
     */
    public function getCustomer(int $tenantId, array $param)
    {

        $param['filter'] = append_filter_param($param, 'supplier', 'from_tenant_id', $tenantId);
        $param['filter'] = append_filter_param($param, 'supplier', 'type', 'outside');
//        $param['filter'] = append_filter_param($param, 'tenant_authentication', 'status', 'active');
//        $param['filter'] = append_filter_param($param, 'tenant_authentication', 'fdd_auth_status', 4);
//        $param['filter'] = append_filter_param($param, 'tenant_authentication', 'fdd_cert_status', 1);

        return $this->find($param['filter']);
    }

    /**
     * 查询客户信息
     * @param array $filter
     * @return mixed
     */
    private function find(array $filter)
    {
        $supplierModel = model(SupplierModel::class);
        // 查询数据
        $queryFields = [
            'supplier.id',
            'supplier.user_id',
            'supplier.type',
            'supplier.tenant_id',
            'supplier.from_tenant_id',
            'supplier.step_category_ids',
            'supplier.created',
            'supplier.updated',
            'supplier.created_by',
            'supplier.framework_agreement_contract_id',
            'supplier.framework_agreement_status',
        ];
        $data = $supplierModel
            ->join("LEFT JOIN tenant ON tenant.id=supplier.from_tenant_id")
            ->join("LEFT JOIN tenant_authentication ON tenant_authentication.tenant_id = supplier.tenant_id")
            ->field(implode(',', $queryFields))
            ->where($filter)
            ->order('created desc')
            ->find();

        if (empty($data)) {
            return null;
        }

        $userIds = [$data['created_by'], $data['user_id']];
        $users = [];
        if (!empty($userIds)) {
            $users = model(UserModel::class)->where(['id' => ['IN', implode(',', $userIds)]])->select();
            $users = array_column($users, null, 'id');
        }

        $tenantAuthenticationData = model(TenantAuthenticationModel::class)->where(['tenant_id' => $data['tenant_id']])
            ->field("service_category,company_customer_service,json,fdd_auth_url", true)
            ->find();
        //每个供应商 对应不同分类的等级数据
        $tenantStepCategoryLevelData = model(TenantStepCategoryLevelModel::class)
            ->where([
                'tenant_id' => $data['tenant_id']
            ])
            ->field("uuid,created,updated,created_by", true)
            ->select();
        $data['authentication'] = $tenantAuthenticationData;
        $data['level_data'] = $tenantStepCategoryLevelData;
        $data['creator'] = $users[$data['created_by']] ?? null;
        $data['user'] = $users[$data['user_id']] ?? null;

        return $data;
    }

}